package Homework.Top2;


import Homework.Top1.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class JdbcTest {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入要插入的name");
        String name=sc.next();
        Connection con = DBUtil.getConnection();
        PreparedStatement p1=null,p2=null;
        ResultSet rs = null;
        String sql1="INSERT INTO test01(`name`) VALUES (?);";
        String sql2="SELECT LAST_INSERT_ID();";
        try {
            con.setAutoCommit(false);
            p1=con.prepareStatement(sql1);
            p1.setString(1,name);
            int r1=p1.executeUpdate();
            if (r1 == 1){
                con.commit();
                p2=con.prepareStatement(sql2);
                rs=p2.executeQuery();
                if (rs.next()){
                    System.out.println(rs.getInt("LAST_INSERT_ID()"));
                }
            } else {
                con.rollback();
                System.out.println("添加失败！");
            }
        } catch (SQLException e) {
            try {
                con.rollback();
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            DBUtil.close(p1);
            DBUtil.close(p2);
            DBUtil.close(con);
        }
    }
}
